<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="140px">
      <el-form-item label="企业名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属辖区" prop="xqid">
        <el-cascader :props="props" @change="changeQueryXqid"></el-cascader>
      </el-form-item>
      <el-form-item label="负责人" prop="fzr">
        <el-input
          v-model="queryParams.fzr"
          placeholder="请输入负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="安全人员" prop="safeMember">
        <el-input
          v-model="queryParams.safeMember"
          placeholder="请输入安全人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人联系方式" prop="fzrPhone">
        <el-input
          v-model="queryParams.fzrPhone"
          placeholder="请输入负责人联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="安全人员联系方式" prop="safePhone">
        <el-input
          v-model="queryParams.safePhone"
          placeholder="请输入安全人员联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:company:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-popover
          placement="bottom"
          width="400"
          trigger="click">
          <div>
            <el-upload
              class="upload-demo"
              drag
              :action="importData"
              :headers="headers"
              :on-success="uploadSuccess"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <br>
            <el-link type="primary" :href="importTemplate">下载导入模板</el-link>
          </div>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            slot="reference"
            v-hasPermi="['system:store:import']"
          >导入</el-button>
        </el-popover>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:company:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:company:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属辖区" align="center" prop="deptName" />
      <el-table-column label="企业名称" align="center" prop="name" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="负责人" align="center" prop="fzr" />
      <el-table-column label="安全人员" align="center" prop="safeMember" />
      <el-table-column label="负责人联系方式" align="center" prop="fzrPhone" />
      <el-table-column label="安全人员联系方式" align="center" prop="safePhone" />
      <el-table-column label="重点区域" align="center" prop="imptArea" />
      <el-table-column label="创建人" align="center" prop="createrName" />
      <el-table-column label="操作人" align="center" prop="operterName" />
      <el-table-column label="操作时间" align="center" prop="operTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:company:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:company:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="企业名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="所属辖区ID" prop="deptId">
          <el-cascader :placeholder="form.deptName" :props="props" @change="changeXqid"></el-cascader>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="经度" prop="lon">
          <el-input v-model="form.lon" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="企业人数" prop="comNum">
          <el-input-number size="small" v-model="form.comNum" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="负责人" prop="fzr">
          <el-input v-model="form.fzr" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人联系方式" prop="fzrPhone">
          <el-input v-model="form.fzrPhone" placeholder="请输入负责人联系方式" />
        </el-form-item>
        <el-form-item label="安全人员" prop="safeMember">
          <el-input v-model="form.safeMember" placeholder="请输入安全人员" />
        </el-form-item>
        <el-form-item label="安全人员联系方式" prop="safePhone">
          <el-input v-model="form.safePhone" placeholder="请输入安全人员联系方式" />
        </el-form-item>
        <el-form-item label="重点区域" prop="imptArea">
          <el-input v-model="form.imptArea" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompany, getCompany, delCompany, addCompany, updateCompany, importData, importTemplate } from "@/api/system/company";
import { getdeptByparentid } from '@/api/system/dept'
import {getToken} from "@/utils/auth";
import store from "@/store";

export default {
  name: "Company",
  data() {
    return {
      importData,
      importTemplate,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业基础信息表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        name: null,
        address: null,
        fzr: null,
        safeMember: null,
        fzrPhone: null,
        safePhone: null,
        imptArea: null,
        creater: null,
        operter: null,
        operTime: null,
        status: null
      },
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "所属辖区ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
      },
      props: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          const params = {
            parentid: ['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId,
            deptType: '0'
          }
          console.log('node', node)
          params.parentid = node.value || (['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId)
          const { level } = node;
          getdeptByparentid(params).then(res => {
            const nodes = res.data.map(item => {
              return {
                value: item.deptId,
                label: item.deptName,
                leaf: level >= 1
              }
            })
            resolve(nodes)
          })
        }
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询企业基础信息列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        name: null,
        address: null,
        fzr: null,
        safeMember: null,
        fzrPhone: null,
        safePhone: null,
        comNum: 1,
        imptArea: null,
        creater: null,
        createTime: null,
        operter: null,
        operTime: null,
        status: null
      };
      this.resetForm("form");
    },
    uploadSuccess(res, file, fileList) {
      console.log('upres', res, file, fileList)
      this.$message({
        message: res.code === 200 ? '导入成功！' : res.msg,
        type: res.code === 200 ? 'success' : 'error'
      })
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业基础信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCompany(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业基础信息";
      });
    },
    changeXqid(v) {
      this.form.deptId = v[v.length - 1]
    },
    changeQueryXqid(v) {
      this.queryParams.pdeptId = v[v.length - 1]
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCompany(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompany(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除企业基础信息编号为"' + ids + '"的数据项？').then(function() {
        return delCompany(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/company/export', {
        ...this.queryParams
      }, `company_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
